package com.neuedu.springmvc.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Response;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Controller
public class FileController {

    public static final String BASE_DIR = "D:\\upload";

    /**
     * 接受浏览器上传文件的控制器方法
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/upload_file",method = RequestMethod.POST) //只允许post提交
    public String upload(MultipartFile[] myfile  ) throws IOException {

        //myfile 此对象代表上传到服务器的文件句柄，在临时目录,需要转储到指定的目录（D:\\java1upload）

        for (MultipartFile file : myfile) {

            //转储到指定位置
            //生成唯一的文件名
            //转储的目标文件  destFile
            File destFile = new File(BASE_DIR, getNewFileName(file.getOriginalFilename()));
            destFile.createNewFile();
            file.transferTo(destFile); //转储的方法
        }
        return "success";
    }


    /**
     * 展示文件列表
     * @param model
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/list")
    public String list(Model model  ) throws IOException {

        File dir = new File(BASE_DIR);


        model.addAttribute("fileList",dir.listFiles());

        return "file_list";
    }



    @RequestMapping(value = "/download")
    public void download(Model model  , String filename , HttpServletResponse response) throws IOException {



        //response.setContentType("application/object");
        response.setHeader("Content-Disposition","attachment;filename="+filename);

        //即将下载的文件
        File file = new File(BASE_DIR,filename);
        InputStream is = new FileInputStream(file);
        ServletOutputStream os = response.getOutputStream();

        byte[] buffers = new byte[1024];
        int len = 0;
        while(    (len = is.read(buffers) ) != -1) {
            os.write(buffers,0,len);
            os.flush();
        }

        is.close();
        os.close();

    }



    @RequestMapping(value = "/download2")
    public ResponseEntity<byte[]> download2( String filename ) throws IOException {


        File file = new File(BASE_DIR,filename);

        return ResponseEntity.ok().
                //header(HttpHeaders.CONTENT_TYPE,"application/octet-stream").
                //通知浏览器以什么方式处理响应结果（直接打开，附件下载）
                 header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"").
                 body(FileUtils.readFileToByteArray(file));

    }






    /**
     * 根据原始文件名的扩展名，生成一个唯一的新的文件名
     * @param orgName
     * @return
     */
    public static String getNewFileName(String orgName){

//        String newFileName = UUID.randomUUID().toString();
        /**
         * d36f2ac3-d634-420b-a9ef-7daa6c701b29
         * 9f249028-63a6-4843-8227-c6f40d3a73c3
         * c13d36da-4f8f-4832-9868-de87e4eed458
         * 1c2266bd-7cb9-4291-859f-0472b2f5cbe9
         * df056bfb-1657-4598-b27d-836886b72f5b
         */


        String newFileName = UUID.randomUUID().toString().replace("-","");
        /**
         * cf4e231a859247248e376ce9dd787a78
         * d7de91b743c546718138ca965d0a6a90
         * 77ee1ebc28f246408794fd9ac7240ebc
         * d937977c2c13408280ed2bbddb948af5
         * c5d69044f56c4fb5a5df07d21f8097d2
         * ca0782562bd34f17838a18b39d7b8833
         * f1bea843ff694d5aabf590849ef3d3be
         */

        newFileName += orgName.substring(orgName.lastIndexOf("."));
        /**
         * c2e15fc3b7eb4d028bcaa270c4fd817c.txt
         * aad35ed22c674f8781f60ba581b031e6.txt
         * 7aa862adc57a481aa41bcb91ae910104.txt
         * ff9d14279bf545ad99b0668c92d8828b.txt
         * 025ae8b3d61a4e6cb8516af3da0ba215.txt
         */


        return newFileName;
    }

}
